<template>
  <!--融资余额-->
  <div class='g-content-wrapper'>
    <header-top class="header">融资余额</header-top>
    <div class='g-content'>
      <state></state>
      <div class='balance'>
        <tab-bar class='tabBar' :tab-bar='menuTabBar' :on-selected='onBarSelected'></tab-bar>
        <!--图表-->
        <div style="position: relative">
          <loading></loading>
          <error :reload="fetchChartData"></error>
          <div class="legend g-legend-wrapper">
            <span class="g-legend-title g-font-f4">
              <span class="g-font-f5">{{chartTime | dashFormat}}</span>
            </span>
            <div class="g-legend-content">
              <span class="g-font-f5 g-legend-item red">融资余额
                <span class="number">{{finance | largeNumFormat}}</span>{{finance | textOfLg}}
              </span>
              <span class="g-font-f5 g-legend-item blue">上证指数
               <span class="number">{{shIndex | toFixed(0)}}</span>
               </span>
              <span class="g-font-f5 g-legend-item orange">较前一日变化
               <span class="number">{{change | largeNumFormat}}</span>{{change | textOfLg}}
               </span>
            </div>
          </div>
          <div class="chart">
            <div class='chartInner' ref="chartInner"></div>
          </div>
        </div>
        <div class="interval"></div>
        <!--明细-->
        <detail-list :list-data="listData" list-type="b" :head-content = 'headContent' :update-time="ListUpdateTime">融资融券余额明细</detail-list>
        <div class="interval"></div>
        <div class='comment'>
          <h1 class='comment-title'>融资余额</h1>
          <p>1.	什么是融资<br/>
            融资交易就是投资者以资金或证券作为质押，向证券公司借入资金用于证券买入，并在约定的期限内偿还借款本金和利息。<br/>
            2.	什么是融资余额<br/>
            融资余额指投资者每日融资买进与归还借款间的差额的累积。融资余额增加，表示市场趋向买方；反之则趋向卖方。<br/>
            3.	融资余额有什么用<br/>
            融资余额若长期增加时，表示投资者心态偏向买方，市场人气旺盛，属于强势市场；反之若减少，则属于弱势市场。</p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import headerTop from '@/components/common/HeaderTop.vue'
  import state from '@/components/common/State.vue'
  import tabBar from '@/components/common/TabBar.vue'
  import detailList from '@/components/common/DetailList.vue'
  import echarts from 'echarts/lib/echarts';
  import constant from '@/common/constant'
  import { financeProcess, destruct } from '@/common/common'
  import { pointFormat, dashFormat } from '@/filters/dataTime'
  import { textOfLg } from '@/filters/legendFormat';
  import remoteDAO from '@/common/remoteDAO'
  import tools from 'libs/common/tools'
  const chartConfig = constant.chartConfig;
  const _options = {
    color: ['#ff8420', '#6c9bd2', '#e84b4b'],
    grid: {
      top: '15%',
      bottom: '15%',
      left: '15%',
      right: '15%'
    },
    tooltip: {
      ...chartConfig.tooltip
    },
    xAxis: {
      type: 'category',
      splitLine: chartConfig.splitLine,
      axisTick: chartConfig.axisTick,
      axisLine: chartConfig.axisLine,
      axisLabel: chartConfig.axisLabel
    },
    yAxis: [
      {
        type: 'value',
        name: '融资余额(亿元)',
        splitLine: chartConfig.splitLine1,
        axisLabel: chartConfig.axisLabel,
        axisTick: chartConfig.axisTick,
        nameTextStyle: chartConfig.nameTextStyle,
        axisLine: chartConfig.axisLine1,
        min: 0
      },
      {
        type: 'value',
        name: '上证指数',
        axisLine: chartConfig.axisLine1,
        splitLine: chartConfig.splitLine,
        axisLabel: chartConfig.axisLabel,
        axisTick: chartConfig.axisTick,
        nameTextStyle: chartConfig.nameTextStyle
      }
    ],
    series: [
      {
        name: '较前一日变化',
        type: 'line',
        symbol: 'none',
        lineStyle: {
          normal: {
            width: 1
          }
        },
        yAxisIndex: 0
      },
      {
        name: '上证指数',
        type: 'line',
        lineStyle: chartConfig.lineStyle,
        symbol: 'none',
        smooth: true,
        yAxisIndex: 1
      },
      {
        name: '融资余额',
        type: 'bar',
        yAxisIndex: 0
      }]
  };
//  let midPoint;

  export default{
    name: 'finance',
    data() {
      return {
        menuTabBar: [{name: '近一月'}, {name: '近三月'}, {name: '近一年'}],
        msgBar: 0,
        ListUpdateTime: '____-__-__（昨日）',
        headContent: ['名称/代码', '融资余额', '融券余额'],
        listData: [],
        chartData: {},
        tmpData: {},
        dataIndex: ''
      }
    },
    components: {
      headerTop,
      state,
      tabBar,
      detailList
    },
    filters: {
      textOfLg,
      dashFormat,
      toFixed (arg1, arg2) {
        return Number(arg1).toFixed(arg2)
      },
      largeNumFormat (num) {
        let res = destruct(Number(num))
        return res.isNegative ? '-' + res.num : res.num
      }
    },
    computed: {
      chartTime () {
        return this.tmpData.xTime ? this.tmpData.xTime[this.dataIndex] : ''
      },
      finance () {
        return this.tmpData.finance ? this.tmpData.finance[this.dataIndex] : '-'
      },
      shIndex () {
        return this.tmpData.shIndex ? this.tmpData.shIndex[this.dataIndex] : '-'
      },
      change () {
        return this.tmpData.change ? this.tmpData.change[this.dataIndex] : '-'
      }
    },
    methods: {
      onBarSelected (index) {
        if (this.msgBar == index) return;
        this.$store.dispatch('showLoading');
        this.msgBar = index;
        this.fetchChartData(index)
      },
      chartSelected(params) {
        this.dataIndex = params[0].dataIndex;
      },
      async fetchChartData () {
        let pType = [30, 90, 365][this.msgBar];
        try {
          let [index, fund] = await Promise.all([
            remoteDAO.invoke(constant.InterfaceEnum.GET_DAYS_INDEX, {type: 1, pType}),
            remoteDAO.invoke(constant.InterfaceEnum.GET_FINANCE, {type: this.msgBar})
          ])
          let res = this.tmpData = financeProcess(index, fund)
          console.log(this.tmpData)
//          midPoint = (Math.max.apply(null, res.shIndex) + Math.min.apply(null, res.shIndex)) / 2;
          let minChange = Math.min.apply(null, res.change)
          minChange = minChange < 0 ? Math.abs(minChange) : 0
          let options = {
            tooltip: {
              formatter: this.chartSelected
            },
            xAxis: {data: res.xTime.map(v => pointFormat(v))},
            series: [
              {data: res.change.map(v => (Number(v) + minChange) / 100000000)},
              {data: res.shIndex},
              {data: res.finance.map(v => v / 100000000)}]
          };
          this.myChart.setOption(options);
          this.$store.dispatch('hideLoading');
          this.dataIndex = res.xTime.length - 1
        } catch (err) {
          alert(err);
          this.$store.dispatch('showError');              //  请求失败   error显示
        }
      },
      async fetchListData () {
        try {
          let res = await remoteDAO.invoke(constant.InterfaceEnum.GET_YST_FINANCE, null);
          this.listData = res
          let d = new Date().getTime() - 1000 * 60 * 60 * 24;
          this.ListUpdateTime = `${tools.DateFormat(new Date(d), 'yyyy-MM-dd')}（昨日）`
        } catch (err) {
          // alert(err)
        }
      }
    },
    created() {
      this.fetchChartData();
      this.fetchListData();
    },
    mounted() {
      this.$store.dispatch('showLoading');
      this.myChart = echarts.init(this.$refs['chartInner']);
      this.myChart.setOption(_options);
    },
    beforeDestroy () {
      echarts.dispose(this.myChart);
    }
  }
</script>
<style lang="less" scoped="">
  @import '../../assets/css/cssReset';
  @import '../../assets/css/variables';
  .chartInner{
    height: 2.485rem;
  }
  .g-legend-item{
    line-height: 1.5;
    padding-right: .1rem;
    word-break:keep-all;
    white-space:nowrap;
    &:nth-child(1){
      width: 1.34rem;
    }
    &:nth-child(2){
      width: .88rem;
    }
    &:before {
     margin-right: .05rem;
    }
  }
  .g-legend-title{
    width: 22%;
    height: .16rem;
  }
  .tabBar{
    border-top: 1px #ddd solid;
    margin: 0;
    padding: .15rem 0;
  }
</style>
